import React, { PureComponent } from 'react';
import { connect } from 'dva';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Modal,
  message,
  Checkbox,
  Radio,
  Divider,
} from 'antd';
import DescriptionList from 'components/DescriptionList';

import {
  roleDistribution,
  roleDelete,
  roleAdd,
  roleUpdate,
  permissionList,
  permissionListByRole,
} from '../../services/api';

// eslint-disable-next-line import/first
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './role.less';

const { TextArea } = Input;
// eslint-disable-next-line prefer-destructuring
const confirm = Modal.confirm;
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const statusMap = {
  '0': '禁用',
  '1': '启用',
};

const PAGE_SIZE = 5;

@connect(({ role, loading }) => {
  return {
    role,
    loading: loading.models.role,
  };
})
@Form.create()
export default class List extends PureComponent {
  constructor(props) {
    super(props);
    this.getRid = this.getRid.bind(this);
    this.getKey = this.getKey.bind(this);
    this.getChildren = this.getChildren.bind(this);
  }
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    name: null,
    code: null,
    type: null,
    status: 1,
    description: null,
    configRoleVisible: false,
    permissionList: {
      children: [],
    },
    permisstions: {},
    activeRecordItem: {},
  };

  componentDidMount() {
    this.init();
  }

  async init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });

    const { data } = await permissionList();
    this.setState({
      permissionList: data,
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'role/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'role/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        keyword: fieldsValue.name,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'role/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      name: null,
      code: null,
      type: null,
      status: 1,
      description: null,
    });
  };

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  async handleSave(e) {
    const { name, code, type, status, description } = this.state;
    if (!name) {
      return message.error('角色名称不能为空');
    }
    if (!code) {
      return message.error('角色编码不能为空');
    }
    if (!type) {
      return message.error('角色类型不能为空');
    }

    await this.doSave();
  }

  async doSave() {
    const { dispatch } = this.props;

    const { id, name, code, type, status, description } = this.state;
    const params = { name, code, type, status, description };

    if (id) {
      params.id = id;
      const response = await roleUpdate(params);

      if (response.code == 200) {
        this.setState({
          modalVisible: false,
        });

        this.init();
      } else {
        message.error(response.message);
      }
    } else {
      const response = await roleAdd(params);

      if (response.code == 200) {
        this.setState({
          modalVisible: false,
        });

        this.init();
      } else {
        message.error(response.message);
      }
    }
  }

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={16} sm={24}>
            <FormItem label="角色名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>

        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <span style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" onClick={this.handleShowModal.bind(this)}>
                新增角色
              </Button>
            </span>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
        </Row>
      </Form>
    );
  }

  handleEdit(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  async handleDelete(item) {
    const { dispatch } = this.props;

    confirm({
      title: '确认删除',
      content: '是否删除？',
      onOk: async () => {
        const { errno, errmsg, data } = await roleDelete({
          id: item.id,
        });
        if (!errno) {
          message.success('删除成功');
          this.init();
        }
      },
      onCancel() {},
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onPermissionChange(field, e) {
    this.setState({
      permisstions: {
        ...this.state.permisstions,
        [field]: e.target.checked,
      },
    });
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  async handleShowConfigRole(item) {
    const hide = message.loading('加载中', 0);

    const { errno, errmsg, data } = await permissionListByRole({
      roleId: item.id,
    });

    const permisstions = {};
    data.map(item => {
      permisstions[`roleId_${item.id}`] = true;
    });

    this.setState({
      activeRecordItem: item,
      configRoleVisible: true,
      permisstions,
    });

    setTimeout(hide, 100);
  }

  handleConfigRole() {
    this.setState({
      configRoleVisible: !this.state.configRoleVisible,
    });
  }

  getRid(key0, key1) {
    const value = this.state.permissionList.children.find(item => item.value == key0);
    if (value) {
      return `roleId_${this.state.permissionList.children.find(item => item.value == key0)[key1]}`;
    }
    return '';
  }

  getKey(key0, key1) {
    const value = this.state.permissionList.children.find(item => item.value == key0);
    if (value) {
      return this.state.permissionList.children.find(item => item.value == key0)[key1];
    }
    return '';
  }

  getChildren(key0) {
    const value = this.state.permissionList.children.find(item => item.value == key0);
    if (value) {
      return this.state.permissionList.children.find(item => item.value == key0).children;
    }
    return [];
  }

  async handleRoleConfigSave() {
    const { permisstions, activeRecordItem } = this.state;

    const permissionIds = [];
    Object.keys(permisstions).map(key => {
      if (permisstions[key]) {
        permissionIds.push(key.split('_')[1]);
      }
    });

    const { errno, errmsg, data } = await roleDistribution({
      id: activeRecordItem.id,
      permissionIds,
    });
    this.setState({
      configRoleVisible: false,
    });
  }

  render() {
    const { role: { data }, loading } = this.props;
    const { selectedRows, modalVisible, permissionList } = this.state;
    if (!permissionList || !permissionList.children || !permissionList.children.length) {
      return null;
    }

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (val, item, index) => (
          <span>{(data.pagination.current - 1) * data.pagination.pageSize + index + 1}</span>
        ),
      },
      {
        title: '角色名称',
        dataIndex: 'name',
      },
      {
        title: '角色编码',
        dataIndex: 'code',
      },
      {
        title: '角色类型',
        dataIndex: 'type',
      },
      {
        title: '角色描述',
        dataIndex: 'description',
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: val => <span>{statusMap[val]}</span>,
      },
      {
        title: '操作',
        dataIndex: '',
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleEdit.bind(this, item)}>
              编辑
            </a>&nbsp;
            <a onClick={this.handleDelete.bind(this, item)}>删除</a>&nbsp;<a
              onClick={this.handleShowConfigRole.bind(this, item)}
            >
              权限分配
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="角色列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              rowKey="id"
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          style={{ width: '800px' }}
          title={!this.state.id ? '新增角色' : '编辑角色'}
          visible={this.state.modalVisible}
          onOk={this.handleSave.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <DescriptionList size="large" title="" col="1">
            <Description term="角色名称">
              <Input value={this.state.name} onChange={this.handleOnchange.bind(this, 'name')} />
            </Description>
            <Description term="角色编码">
              <Input value={this.state.code} onChange={this.handleOnchange.bind(this, 'code')} />
            </Description>
            <Description term="角色类型">
              <RadioGroup onChange={this.onRadioChange.bind(this, 'type')} value={this.state.type}>
                <Radio value="系统角色">系统角色</Radio>
                <Radio value="业务角色">业务角色</Radio>
              </RadioGroup>
            </Description>
            <Description term="角色状态">
              <RadioGroup
                onChange={this.onRadioChange.bind(this, 'status')}
                value={this.state.status}
              >
                <Radio value={1}>启用</Radio>
                <Radio value={0}>禁用</Radio>
              </RadioGroup>
            </Description>
            <Description term="角色描述" termStyle={styles.top}>
              <TextArea
                rows={4}
                value={this.state.description}
                onChange={this.handleOnchange.bind(this, 'description')}
              />
            </Description>
          </DescriptionList>
        </Modal>

        <Modal
          width="90%"
          title="权限设置"
          visible={this.state.configRoleVisible}
          onOk={this.handleRoleConfigSave.bind(this)}
          onCancel={this.handleConfigRole.bind(this)}
        >
          <Divider orientation="left">
            <Checkbox
              checked={this.state.permisstions[this.getRid('resource', 'id')]}
              onChange={this.onPermissionChange.bind(this, this.getRid('resource', 'id'))}
            >
              <span className={styles.menu}>{this.getKey('resource', 'name')}</span>
            </Checkbox>
          </Divider>

          {this.getChildren('resource').map(item => {
            return (
              <DescriptionList key={item.id} size="large" col="3" style={{ marginBottom: 32 }}>
                <Checkbox
                  checked={this.state.permisstions[`roleId_${item.id}`]}
                  onChange={this.onPermissionChange.bind(this, `roleId_${item.id}`)}
                >
                  <span className={styles.menu}>{item.name}</span>
                </Checkbox>
                {item.children.map(item2 => {
                  return (
                    <Checkbox
                      key={item2.id}
                      checked={this.state.permisstions[`roleId_${item2.id}`]}
                      onChange={this.onPermissionChange.bind(this, `roleId_${item2.id}`)}
                    >
                      {item2.name}
                    </Checkbox>
                  );
                })}
              </DescriptionList>
            );
          })}

          <Divider orientation="left">
            <Checkbox
              checked={this.state.permisstions[this.getRid('tag', 'id')]}
              onChange={this.onPermissionChange.bind(this, this.getRid('tag', 'id'))}
            >
              <span className={styles.menu}>{this.getKey('tag', 'name')}</span>
            </Checkbox>
          </Divider>

          {this.getChildren('tag').map(item => {
            return (
              <DescriptionList key={item.id} size="large" col="3" style={{ marginBottom: 32 }}>
                <Checkbox
                  checked={this.state.permisstions[`roleId_${item.id}`]}
                  onChange={this.onPermissionChange.bind(this, `roleId_${item.id}`)}
                >
                  <span className={styles.menu}>{item.name}</span>
                </Checkbox>
                {item.children.map(item2 => {
                  return (
                    <Checkbox
                      key={item2.id}
                      checked={this.state.permisstions[`roleId_${item2.id}`]}
                      onChange={this.onPermissionChange.bind(this, `roleId_${item2.id}`)}
                    >
                      {item2.name}
                    </Checkbox>
                  );
                })}
              </DescriptionList>
            );
          })}

          <Divider orientation="left">
            <Checkbox
              checked={this.state.permisstions[this.getRid('match', 'id')]}
              onChange={this.onPermissionChange.bind(this, this.getRid('match', 'id'))}
            >
              <span className={styles.menu}>{this.getKey('match', 'name')}</span>
            </Checkbox>
          </Divider>

          {this.getChildren('match').map(item => {
            return (
              <DescriptionList key={item.id} size="large" col="3" style={{ marginBottom: 32 }}>
                <Checkbox
                  checked={this.state.permisstions[`roleId_${item.id}`]}
                  onChange={this.onPermissionChange.bind(this, `roleId_${item.id}`)}
                >
                  <span className={styles.menu}>{item.name}</span>
                </Checkbox>
                {item.children.map(item2 => {
                  return (
                    <Checkbox
                      key={item2.id}
                      checked={this.state.permisstions[`roleId_${item2.id}`]}
                      onChange={this.onPermissionChange.bind(this, `roleId_${item2.id}`)}
                    >
                      {item2.name}
                    </Checkbox>
                  );
                })}
              </DescriptionList>
            );
          })}

          <Divider orientation="left">
            <Checkbox
              checked={this.state.permisstions[this.getRid('system', 'id')]}
              onChange={this.onPermissionChange.bind(this, this.getRid('system', 'id'))}
            >
              <span className={styles.menu}>{this.getKey('system', 'name')}</span>
            </Checkbox>
          </Divider>

          {this.getChildren('system').map(item => {
            return (
              <DescriptionList key={item.id} size="large" col="3" style={{ marginBottom: 32 }}>
                <Checkbox
                  checked={this.state.permisstions[`roleId_${item.id}`]}
                  onChange={this.onPermissionChange.bind(this, `roleId_${item.id}`)}
                >
                  <span className={styles.menu}>{item.name}</span>
                </Checkbox>
                {item.children.map(item2 => {
                  return (
                    <Checkbox
                      key={item2.id}
                      checked={this.state.permisstions[`roleId_${item2.id}`]}
                      onChange={this.onPermissionChange.bind(this, `roleId_${item2.id}`)}
                    >
                      {item2.name}
                    </Checkbox>
                  );
                })}
              </DescriptionList>
            );
          })}
        </Modal>
      </PageHeaderLayout>
    );
  }
}
